import React from 'react'
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
import {Tools,SearchBar,Icon,Flex,Button,ActionSheet } from 'weaver-mobile';
import { ListViewPage,SearchAdvanced,RouteLayout } from 'weaver-mobile-page';
import {toThousands,takeOutThousands} from '../../util/common';
import {openWorkFlow,resetNavBar} from '../../util/pulic-func';
import { withRouter } from 'react-router-dom';
const getLabel = Tools.getLabel;

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}

@withRouter
@inject ('walletStore','baseStore')
@observer
class Submit extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            selectedKey:0,  //底部
        }
    }

    componentDidMount() {
        
    }


    componentWillUnmount(){
        // ActionSheet.close();
    }

    

    render() {
        const {baseStore} = this.props;
        const { invoiceCloudInfo } = baseStore;  

        const data=[
            { title: getLabel(516432,'发票录入') , icon:"invoice-input" , key: 0 },
            { title: getLabel(517379,'生成记账'), icon:"write-down-a-note" , key: 1 },
            { title: getLabel(383848,'发起报销') , icon:"initiate-reimbursement" , key: 2 },
        ] 

        return (
            <div style={{ height: "100%" }}>
                {invoiceCloudInfo.invoiceCloud === false && <Ec_Submit footerClick={this.footerClick} data={data}/>}
                {invoiceCloudInfo.invoiceCloud === true && <Cloud_Submit footerClick={this.footerClick} data={data}/>}
            </div>
        )
    }

    //生成记账
    footerClick = (key) =>{
        const {walletStore} = this.props;
        const {invoiceCreatWorkflow,workflowSelect,wfInfo,nameQuery,stateParams} = walletStore;
        if(key == '0'){//发票录入
            resetNavBar();
            this.props.history.push(`/reception`)
        }else if(key == '1'){//生成记账
            if(stateParams.onRowSelect.length === 0) return;

            let str = stateParams.onRowSelect.join(',');
            this.props.history.push(`/remember?invoiceIds=${str}`)
        }else {//发起报销
            if(stateParams.onRowSelect.length === 0) return;
    
            let allMonth = workflowSelect;
            ActionSheet.showActionSheetWithOptions({
                options: allMonth,
                cancelButtonIndex: allMonth.length - 1,
                maskClosable: true,
                'data-seed': 'logId',
                wrapProps,
            },  
            (buttonIndex) => {
                if(buttonIndex != allMonth.length - 1){
                    let params = {
                        workflowId:workflowSelect[buttonIndex].id,
                        id:wfInfo.id
                    }
                    invoiceCreatWorkflow(params,(value)=>{
                        openWorkFlow('view',value.requestId,()=>{
                            this.doSerch(nameQuery,false)
                        });
                    })
                    
                }
                    
            });    
        }
        this.setState({selectedKey:key});
    }      

}

export default Submit;


/*
*   微报账 tab页对应的页面
*/
@withRouter
@inject ('walletStore')
@observer
class Ec_Submit extends React.Component {
    constructor(props){
        super(props);
    }

    componentWillMount(){
        const {location:{pathname},walletStore} = this.props;
        const {initStore} = walletStore;
        initStore(pathname)
    }
    

    componentDidMount() {

    }

    componentWillUnmount(){

    }

    render() {
        const {walletStore} = this.props;
        const { selectKeyTop } = walletStore;
        let diffkey = selectKeyTop; 

        return (
            <div style={{ height: "100%" }}>
                {this.getListLayout(diffkey)}
            </div>
        )
    }

    getListLayout = (diffkey)=>{
        const {walletStore} = this.props;
        const {listViewPageData,selectKeyTop,stateParams,setStateParams} = walletStore;

        let comment =(
            <div className={ listViewPageData.data.length > 0 ? `fna-wallet-tabPage` : `fna-wallet-tabPage bgColor_fff`}>
                <div>
                    {this.getSearch()}
                    {this.getTabPage(diffkey)}
                    {/* <SearchAdvanced
                        store={search}
                        buttonGroupData={this.getSearchFormBtn()} 
                    /> */}
                    {selectKeyTop == 0 ? 
                        <footer className={`fna-wallet-footer`} >
                                    
                            {stateParams.isSelect && <div className={`fna-wallet-footer-left`}>
                                {listViewPageData.isSelectedAll ? 
                                <div onClick={()=>{listViewPageData.selectNone();setStateParams({onRowSelect:[],allMoney:0})}}><Icon type="check-circle" color={'#55b1f9'} size={'sm'} /><span>{getLabel('387379','取消全选')}</span></div> 
                                : 
                                <div onClick={()=>{listViewPageData.selectAll();this.onRowSelect([],listViewPageData.data,true)}}><Icon type="uncheck" color={'#ccc'} size={'sm'} /><span>{getLabel('556','全选')}</span></div>}
                            </div>}
                            <div className={stateParams.isSelect ? `fna-wallet-footer-right` : `fna-wallet-footer-right fna-wallet-footer-right-isSelect`}>
                                {this.props.data.map( item =>(
                                    <div key={item.key} 
                                        className={ item.key == '0' ? 'fna-tab-bar-select' : (stateParams.onRowSelect.length > 0 ? 'fna-tab-bar-select' : 'fna-tab-bar-unselect') }
                                        // className={'fna-tab-bar-select'}
                                        onClick={()=>{this.props.footerClick(item.key)}}>

                                        <Icon type={item.icon} size={'sm'} />{item.title}
                                    </div>
                                ))}
                            </div>
                        </footer>
                        :
                        <footer className={`fna-wallet-footer`} >
                            <Button type="primary"  style={{'border':0}} onClick={()=>{this.props.history.push('/reception')}}>{getLabel(516432,'发票录入')}</Button>
                        </footer>
                    }                    
                </div>
            </div>
        );

        return comment
    }

    //获取顶部搜索蓝
    getSearch = () =>{
        const {walletStore,history} = this.props;
        const {search,nameQuery,changeSearchValue,setNameQuery,layout,setNowPath} = walletStore;

        let comment;
        comment = <SearchBar
            className="search-select"
            placeholder={getLabel(518093,'请输入发票类型')}
            value={nameQuery}
            onChange={(val) => changeSearchValue(val)}
            showExtraButton
            extraButton={[
                { key: 'advanced', show: <Icon key="filter-o" type="filter-o" /> },
            ]}
            // onChange={val => updateAdSearchSubject(val)}
            onExtraButtonClick={(key) => { 
                if(key === 'advanced'){
                    history.push(layout.path);
                }
            }}
            onSubmit={(value)=>this.doSerch(value)}
            onClear={()=>{setNameQuery();this.doSerch('')}}
        />
        
        return comment;
    }
    
    //获取 tabPage
    getTabPage = (diffkey) =>{
        const { walletStore } = this.props;
        const { selectKeyTop,mark,rememberGroup,stateParams,setStateParams,listViewPageData } = walletStore;

      
        let comment;
        comment = 
            <div>
                <div className={`fna-wallet-select`}>
                    {selectKeyTop == '0' ? 
                        (stateParams.isSelect ? 
                            <div className={"accountBook-isSelect"}>
                                <span>{getLabel(18609,'共')}<span>{stateParams.onRowSelect.length}</span>{getLabel(18256,'条')}</span><i>{getLabel(358,'合计')}：</i><em>{toThousands(stateParams.allMoney.toFixed(2))}</em>
                                <div onClick={()=>{
                                    setStateParams({onRowSelect:[],allMoney:0});
                                    listViewPageData.selectNone();
                                    setStateParams({isSelect:false})
                                }}>{getLabel(387379,'取消全选')}</div>
                            </div> 
                            : 
                            <div className={"accountBook-noSelect"} >
                                {this.getOrderLayout(mark,rememberGroup)}
                                <div className={'fna-wallet-orderLayout-rigth'} onClick={()=>{setStateParams({isSelect:true})}}>{getLabel(556,'全选')}</div>
                            </div>
                        )
                        :
                        this.getOrderLayout(mark,rememberGroup)
                    }
                    
                </div>
            </div>

        
        return (
            <div className={`fna-wallet-invoice`}>
                {comment}

                <ListViewPage.Normal
                    multipleCheck={true}
                    rowKey={'id'}
                    style={{height:"calc(100% - 130px)"}}
                    className={'wf-agent-list-view-page'}
                    showCheck={stateParams.isSelect}
                    store={listViewPageData}
                    getTemplate={this.getTemplate}
                    onRowSelect={(v,d)=>{this.onRowSelect(v,d)}}
                    key={diffkey}
                    onRowClick={(value)=>{this.props.history.push(`/detailPage?invoiceId=${value.id}`);}}
                />
            </div>
        )     

    } 
    
    //获取顶部 排序布局
    getOrderLayout = (markList,dataList) =>{
        return (
            <div className={'fna-wallet-orderLayout-left'}>
                <Flex className={'fna-flex-img fna-flex-img-03'}>
                    {dataList.map( item => {
                        let _key = item.key;
                        //0 ：降序  箭头向下 从大到小
                        let _class = (markList[_key] === 0) ? 'sanjiao_down' : ( markList[_key] === 1 ? 'sanjiao_up' : 'sanjiao_none');

                        let conment = [];
                        {
                            conment = [
                                <Flex.Item key={_key}  className={`fna-flex-img-item`} style={{position:'relative'}} 
                                    onClick={()=>{
                                        let  value = 0;
                                        if(markList[_key] != ''){
                                            value = markList[_key];
                                        };
                                        this.onClickFn({[_key]: (parseInt(value)+1)%2})}
                                    }
                                >
                                    
                                    <div style={_class == 'sanjiao_none' ? {color:'#969BA6'} : {color:'#55B1F9'}} className={`fna-flex-img-item-text`} >
                                        {item.title} 
                                        {_class == 'sanjiao_none' ? 
                                            <Icon type={''} color={'#fff'}/> 
                                            : 
                                            (_class == 'sanjiao_up' ? <Icon type={'icon-up'} color={'#55B1F9'}/> : <Icon type={'icon-down'} color={'#55B1F9'} />) 
                                        }
                                    </div>
                                </Flex.Item>
                            ]
                        }
                        
                        return conment;
                    })}
                </Flex>
            </div>
        )
    }  

    //获取模板  报销流程
    getTemplate = (template) => {
        const newTemplate = {
            default: [
                {
                    key: 'col1',
                    // style: { flex: '0 0 auto'},
                    render: (data) => {
                        let {id,invoiceNumber,billingdate,seller,taxincludedprice,invoicesource_newspan} = data;
                        // console.log('data',data)
                        return(
                            <div key={id} style={{backgroundColor: '#F3F7FE', backgroundClip: 'padding-box',paddingTop:'10px',paddingBottom:'10px'}}>
                                <div className={"fna-incoice-v"}>
                                    <h4><div><span>{getLabel(900,'发票号码')}</span><span>{invoiceNumber}</span></div></h4>
                                    <img src="/images/fna/fnaMobile/incoice-split.png" />
                                    <div>{getLabel(17213,'开票日期')} : {billingdate}</div>
                                    <div>{getLabel(131005,'销售方')} : {seller}</div>
                                    <div>{getLabel(131011,'价税合计')} : {taxincludedprice}</div>
                                    <div>{getLabel(132203,'发票来源')} : {invoicesource_newspan}</div>
                                </div>
                            </div>
                        )
                    }
                },  

                    
            ],
        };

        return newTemplate;
    }       
    
    doSerch = (value) =>{
        const { walletStore} = this.props;
        const {getTicketHolderList,selectKeyTop,mark,options,advancedItem,setStateParams} = walletStore;
        const {form} = advancedItem;
        const {formParams} = form;

        setStateParams({onRowSelect:[],allMoney:0});
        value = value.trim();
        


        if(value == ''){
            form.updateField('advQry_invoiceType', '');
        }else{
            for(let i=0;i<options.length;i++){
                if(options[i].showname == value){
                    form.updateField('advQry_invoiceType', options[i].key);
                    break;
                }
            }
        }
        

        let params = {
             ...form.formParams,  //考虑到上面更新了 from ，重新取值
            status:selectKeyTop,
            nameQuery:value
        }

       
        let orderKey = '';
        for(let k in mark){
            if(mark[k] === 0 || mark[k] === 1){
                orderKey = k;
            }
        }

        params = Object.assign(params,{
            orderKey:orderKey,
            order:mark[orderKey]
        })

        getTicketHolderList(params);
    }    
    
    //选中 复选框
    onRowSelect = (value,datas,selectAll)=>{
        const {walletStore} = this.props;
        const {setWfInfo,getInvoiceCreatWorkflow,setStateParams} = walletStore;

        let money = 0;
        for(let i=0,len = datas.length;i<len;i++){
            if(!datas[i].disabled){
                let oldMoey = takeOutThousands(datas[i].taxincludedprice);
                money += parseFloat(oldMoey);
                selectAll ? value.push(datas[i].id) : null;
            }
            
            
        }
        setStateParams({allMoney:money,onRowSelect:value})

        let  str = value.join(',');

        setWfInfo({ id:str })
        getInvoiceCreatWorkflow({
            invoiceIds:str,
        })


    }

    onClickFn = (value) =>{
        const {walletStore} = this.props;
        const {setMark,mark,getTicketHolderList,search,selectKeyTop,nameQuery}  = walletStore;
        const {formParams} = search.form;
        let _obj = {};
        let temp_param = '';
        for(let key in mark){
            for(let k in value){
                if(key == k){
                    _obj[key] = value[k]; 
                    temp_param = key;
                }else{
                    _obj[key] = '';
                }
            }
        }
        setMark(_obj);
        
        getTicketHolderList({
            ...formParams,
            status:selectKeyTop,
            nameQuery:nameQuery,
            orderKey:temp_param,
            order:_obj[temp_param]
        })
       
        
    }      

}


/*
*   发票云
*/
@withRouter
@inject ('walletStore','baseStore')
@observer
class Cloud_Submit extends React.Component {
    componentDidMount(){

        window.addEventListener('message',this.receiver,false);
    }

    componentWillUnmount(){
        window.removeEventListener('message',this.receiver,false)
    }

    render(){
        const { walletStore,baseStore,location:{pathname} } = this.props;
        const { selectKeyTop,listViewPageData,cloudInvoiceId,stateParams,setStateParams } = walletStore;
        const { getInvoiceCloudUrl } = baseStore; 

        return (
            <div style={{height:"calc(100% - 100px)"}}>
                <iframe 
                    className='ec-iframe' 
                    src={getInvoiceCloudUrl('wallet',0,{status:selectKeyTop})}
                    style={{width:'100%',height:'100%',border:'0'}}
                    id={"myIframe"} 
                    key={selectKeyTop}
                ></iframe>

                {selectKeyTop == 0 ? 
                    <footer className={`fna-wallet-footer`} >
                                
                        {stateParams.isSelect && <div className={`fna-wallet-footer-left`}>
                            {listViewPageData.isSelectedAll ? 
                            <div onClick={()=>{listViewPageData.selectNone();setStateParams({onRowSelect:[],allMoney:0})}}><Icon type="check-circle" color={'#55b1f9'} size={'sm'} /><span>{getLabel('387379','取消全选')}</span></div> 
                            : 
                            <div onClick={()=>{listViewPageData.selectAll();this.onRowSelect([],listViewPageData.data,true)}}><Icon type="uncheck" color={'#ccc'} size={'sm'} /><span>{getLabel('556','全选')}</span></div>}
                        </div>}
                        <div className={stateParams.isSelect ? `fna-wallet-footer-right` : `fna-wallet-footer-right fna-wallet-footer-right-isSelect`}>
                            {this.props.data.map( item =>(
                                <div key={item.key} 
                                    className={ item.key == '0' ? 'fna-tab-bar-select' : (stateParams.onRowSelect.length > 0 ? 'fna-tab-bar-select' : 'fna-tab-bar-unselect') }
                                    // className={'fna-tab-bar-select'}
                                    onClick={()=>{this.props.footerClick(item.key)}}>

                                    <Icon type={item.icon} size={'sm'} />{item.title}
                                </div>
                            ))}
                        </div>
                    </footer>
                    :
                    <footer className={`fna-wallet-footer`} >
                        <Button type="primary"  style={{'border':0}} onClick={()=>{this.props.history.push('/reception')}}>{getLabel(516432,'发票录入')}</Button>
                    </footer>
                }   
               
            </div>
        )
    }


    receiver = (event) =>{
        const {invoiceCloudInfo} = this.props.baseStore;
        if (invoiceCloudInfo.jsUrl != event.origin) return;
        let returnData = event.data;
        console.log('submit------returnData',returnData);

        const {walletStore} = this.props;
        const {setWfInfo,getInvoiceCreatWorkflow,setCloudInvoiceId,setStateParams} = walletStore;

        switch(returnData.type){
            case 'INVOICE' : 
                let arr = [];
                returnData.invoices.map( items =>{
                    arr.push(items.oaid)
                })

                let str = arr.join(',');
                setStateParams({onRowSelect:arr});

                setWfInfo({ id:str })
                getInvoiceCreatWorkflow({
                    invoiceIds:str,
                })
                break;

            case 'ON_WILL_LOAD' :
                setStateParams({onRowSelect:[]});
                // setLoading(true);
                break;
            case 'ON_LOADED' :
                // setLoading(false)
                break;  
            case 'ERROR' :
                if(returnData.ret == '-2'){ this.sendToken();}
                break;
            case 'ON_PREVIEW' : 
                this.props.history.push(`/toWalletCloud?frame=ON_PREVIEW&cloudInvoiceId=${returnData.invoiceId}`);
                setCloudInvoiceId(returnData.invoiceId);
                break;             
            default :
                break;                           
        }


        
    }

    //发送 token
    sendToken = () =>{
        const {baseStore} = this.props;
        const {getInvoiceCloudToken} = baseStore;
        getInvoiceCloudToken({tokenUnusual:1},()=>{
            let childFrame = document.getElementById("myIframe");
            let url = baseStore.invoiceCloudInfo.jsUrl;
            childFrame.contentWindow.postMessage({
                type: 'UPDATE_TOKEN',
                token:baseStore.invoiceCloudInfo.token
            }, url); 
        })

    }



}